package com.be.beadmin.quality.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.utils.ResultModel;
import com.be.beadmin.quality.dto.input.ComplaintFileInfoDto;
import com.be.beadmin.quality.dto.input.CustomComplaintAllDto;
import com.be.beadmin.quality.dto.input.CustomComplaintDto;
import com.be.beadmin.quality.dto.output.CustomComplaintEx;
import com.be.beadmin.quality.dto.output.CustomComplaintExcelEx;
import com.be.beadmin.quality.repository.ComplaintFileInfoRepository;
import com.be.beadmin.quality.service.ComplaintFileInfoService;
import com.be.beadmin.quality.service.CustomComplaintService;
import com.be.beadmin.service.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zjm
 * @date 2023-05-15
 **/
@Api(tags = "质量管理-客户投诉")
@RestController
public class CustomComplaintController {

    private String bucketName = "complaintflie";
    @Autowired
    private CustomComplaintService customComplaintService;
    @Autowired
    private ComplaintFileInfoService complaintFileInfoService;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @ApiOperation(value = "分页获取客户投诉信息 -- 分角色展示")
    @PostMapping(value = "/quality/getCustomComplaintByPage")
    public ResultModel getCustomComplaintByPage(HttpServletRequest request, @RequestBody PageEntity pageEntity) {
        return ResultModel.success(customComplaintService.getCustomComplaintByPage(request, pageEntity));
    }

    //    @ApiOperation(value = "添加客户投诉信息")
//    @PostMapping("/quality/addCustomComplaint")
//    public ResultModel addCustomComplaint(@RequestBody CustomComplaintDto customComplaintDto){
//        customComplaintService.addCustomComplaint(customComplaintDto);
//        return ResultModel.success(ResultModel.ADD);
//    }



    @ApiOperation(value = "QM创建投诉信息")
    @PostMapping("/quality/addCustomComplaintByQm")
    public ResultModel addCustomComplaintByQm(HttpServletRequest request,
                                              @ApiParam(value = "项目ID",required = true) @RequestParam(required = true) String infoId,
                                              @ApiParam(value = "客户名称",required = true) @RequestParam(required = true) String customerName,
                                              @ApiParam(value = "负责人ID",required = true) @RequestParam(required = true) String responsorId,
                                              @ApiParam(value = "联系人ID",required = true) @RequestParam(required = true) String makerId,
                                              @ApiParam(value = "缺陷数量",required = false) @RequestParam(required = false) int bugCount,
                                              @ApiParam(value = "问题描述",required = true) @RequestParam(required = true) String problemTextDes,
                                              @ApiParam(value = "问题类型",required=true) @RequestParam(required = true )String problemType,
                                              @ApiParam(value = "问题图片上传",required = false) @RequestParam(required = false,value="problemPicFile") MultipartFile[] multipartFiles,
                                              @ApiParam(value = "临时措施",required = false) @RequestParam(required = false) String tempSolution,
                                              @ApiParam(value = "投诉时间",required = true) @RequestParam(required = true) String makerTime
                                              ) throws ParseException {
        makerTime=makerTime+":00";
        Date time= df.parse(makerTime);
        customComplaintService.addCustomComplaintByQm(request,infoId,customerName,responsorId,bugCount,problemTextDes,problemType,multipartFiles,tempSolution, bucketName,makerId,time);
        return ResultModel.success(ResultModel.ADD);
    }

    @ApiOperation(value = "QM分析投诉信息")
    @PostMapping("/quality/analyzeCustomComplaintByQm")
    public ResultModel analyzeCustomComplaintByQm(HttpServletRequest request,
                                                  @ApiParam(value = "投诉单id",required = true) @RequestParam String complaintId,
                                                  @ApiParam(value = "根本原因分析及描述",required = false) @RequestParam String baseReasonAnalysis,
                                                  @ApiParam(value = "后续改进方案（描述）",required = false) @RequestParam String improvementText
                                                  ) {
        customComplaintService.analyzeCustomComplaintByQm(request,complaintId,baseReasonAnalysis,improvementText);
        return ResultModel.success(ResultModel.ADD);
    }

    @ApiOperation(value = "根据ID查看该条客户投诉信息new")
    @PostMapping("/quality/getCustomComplaintByIdNew")
    public ResultModel getCustomComplaintByIdNew(@RequestParam String id) {

        return ResultModel.success(customComplaintService.getCustomComplaintByIdNew(id));
    }

    @ApiOperation(value = "修改该条客户投诉信息")
    @PostMapping("/quality/updateCustomComplaint")
    public ResultModel updateCustomComplaint(@RequestBody CustomComplaintDto complaintDto) {
        customComplaintService.updateCustomComplaint(complaintDto);
        return ResultModel.success(ResultModel.UPDATE);
    }


    @ApiOperation(value = "上传客户投诉信息")
    @PostMapping("/quality/submitCustomComplaint")
    public ResultModel submitCustomComplaint(@RequestParam String complaintId) {
        customComplaintService.submitCustomComplaint(complaintId);
        return ResultModel.success(ResultModel.UPDATE);
    }

    @ApiOperation(value = "关闭客户投诉信息")
    @PostMapping("/quality/shutdownCustomComplaint")
    public ResultModel shutdownCustomComplaint(@ApiParam(value = "投诉单id",required = true)@RequestParam String complaintId,
                                               @ApiParam(value = "完成时间",required = true)@RequestParam String finishTime) {
        Date time= DateUtil.computeDate(DateUtil.StringToDate(finishTime),8);
        customComplaintService.shutdownCustomComplaint(complaintId,time);
        return ResultModel.success(ResultModel.UPDATE);
    }

    @ApiOperation(value = "处理客户投诉信息 -- 负责人")  //  少字段内容
    @PostMapping("/quality/handleCustomComplaint")
    public ResultModel handleCustomComplaint(HttpServletRequest request, @ApiParam(value = "投诉单id",required = true) @RequestParam String complaintId,
                                             @ApiParam(value = "原因分析及描述",required = false) @RequestParam String reasonAnalysis,
                                             @ApiParam(value = "后续改进方案（附件）",required = false) @RequestParam(required = false,value="improvementFile") MultipartFile[] multipartFiles
                                             ) {
        try {
            customComplaintService.handleCustomComplaint(request,complaintId,reasonAnalysis,multipartFiles,bucketName);
            return ResultModel.success(ResultModel.UPDATE);
        } catch (Exception e) {
            return ResultModel.error(-1,e.getMessage());
        }

    }


    @ApiOperation(value = "根据ID查看该条客户投诉信息")
    @PostMapping("/quality/getCustomComplaintById")
    public ResultModel getCustomComplaintById(@RequestParam String id) {

        return ResultModel.success(customComplaintService.getCustomComplaintById(id));
    }

    @ApiOperation(value = "修改该条客户投诉信息")
    @PostMapping("/quality/updateCustomComplaintAll")
    public ResultModel updateCustomComplaintAll(@RequestBody CustomComplaintAllDto complaintAllDto) {
        customComplaintService.updateCustomComplaintAll(complaintAllDto);
        return ResultModel.success(ResultModel.UPDATE);
    }

    @ApiOperation(value = "删除客户投诉信息")
    @PostMapping("/quality/delCustomComplaint")
    public ResultModel delCustomComplaint(@RequestParam String id) {
        //需要删除图片吗
        customComplaintService.delCustomComplaint(id);

        return ResultModel.success(ResultModel.DELETE);
    }

    @ApiOperation(value = "完成客户投诉")
    @PostMapping("/quality/finishCustomComplaint")
    public ResultModel finishCustomComplaint(@RequestParam String id) {
        customComplaintService.finishCustomComplaint(id);
        return ResultModel.success(ResultModel.DELETE);
    }

//    @ApiOperation(value = "更新获取客户投诉信息")
//    @PostMapping("/quality/updateCustomComplaint")
//    public ResultModel updateCustomComplaint(@RequestBody CustomComplaintDto customComplaintDto) {
//        customComplaintService.updateCustomComplaint(customComplaintDto);
//        return ResultModel.success(ResultModel.UPDATE);
//    }

    @ApiOperation(value = "导出获取客户投诉信息")
    @PostMapping("/quality/exportCustomComplaint")
    public void exportCustomComplaint(HttpServletRequest request,HttpServletResponse response, @RequestBody PageEntity pageEntity) throws IOException {
        Page<CustomComplaintEx> customComplaintPage = customComplaintService.getCustomComplaintByPage(request,pageEntity);
        List<CustomComplaintEx> customComplaintExes = customComplaintPage.getContent();
        List<CustomComplaintExcelEx> customComplaintExcelExes=customComplaintExes.stream().map(item->{
            CustomComplaintExcelEx excel=new CustomComplaintExcelEx();
            BeanUtils.copyProperties(item,excel);
            return excel;
        }).collect(Collectors.toList());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("CustomComplaint接口", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xls");
        //EasyExcel.write(response.getOutputStream(), CustomComplaintExcelEx.class).sheet("sheet1").doWrite(customComplaintExcelExes);
        ExcelWriterBuilder ewb=EasyExcel.write(response.getOutputStream(), CustomComplaintExcelEx.class);
        ewb.excelType(ExcelTypeEnum.XLS);
        ewb.sheet("sheet1").doWrite(customComplaintExcelExes);
    }
    @ApiOperation(value = "预览上传附件")
    @PostMapping("/quality/getFilePreviewUrl")
    public ResultModel getFilePreviewUrl(@ApiParam(value = "投诉单id",required = true) @RequestParam String customComplaintId,
                                         @ApiParam(value = "附件类型0问题图片1改进措施",required = true) @RequestParam Integer state){
        List<String> urls =customComplaintService.getFilePreviewUrl(customComplaintId,bucketName,state);
        return ResultModel.success(urls);
    }

}